package com.eqdd.yiqidian.ui.gongneng.renshi.train;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.eqdd.nextinputs.StaticScheme;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RecyclerViewCustom;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.CareerListResultBean;
import com.eqdd.yiqidian.bean.rebuild.EmploymentListResultBean;
import com.eqdd.yiqidian.bean.rebuild.LectureListBean;
import com.eqdd.yiqidian.bean.rebuild.TeacherListBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditChooseBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditVEnterBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.ui.base.EditTextActivity;
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity;
import com.eqdd.yiqidian.ui.select.SelectSingleStaffActivity;
import com.eqdd.yiqidian.ui.select.SelectTeacherActivity;
import com.eqdd.yiqidian.utils.BottomSheetUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.text.DecimalFormat;
import java.util.ArrayList;

import io.reactivex.Flowable;

public class AddTrainPlanActivity extends SlimBaseMultiEditActivity {
    private RecyclerViewCustom dataBinding;
    private String contracts;
    private ArrayList<CareerListResultBean> careerListBeans;
    private StringBuilder stringBuilderDepId;
    private StringBuilder stringBuilderDepName;
    private LectureListBean trainListBean;
    private String times;
    private ArrayList<AddTrainTimesActivity.RangeTimeBean> timeBeans;
    private Bundle bundle;
    private BottomSheetDialog bottomSheet;
    private String guid;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_recyclerview);
        initTopTitleBar(View.VISIBLE, "培训计划");
        initTopRightText("提交", v -> {
            if (checkParams()) {
                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.ADD_TRAIN_PLAN)
                        .params("comid", AppConstent.user.getCompanyId())
                        .params("userGuid", AppConstent.user.getGuid())
                        .params("theTheme", setParam(0))
                        .params("theCategory", setParam(1))
                        .params("trainees", setParam(2))
                        .params("personNumber", setParam(4))
                        .params("teacherGuid", contracts)
                        .params("teacherName", setParam(6))
                        .params("budgetedExpense", setParam(5))
                        .params("theTrainTime", times)
                        .params("learningModality", setParam(7))
                        .params("betrainedPostId", trainListBean.getPostIds())
                        .params("courseId", trainListBean.getId())
                        .execute(new DialogCallBack<HttpResult>(this) {
                            @Override
                            public void onSuccess(Response<HttpResult> response) {
                                HttpResult httpResult = response.body();
                                ToastUtil.showShort(httpResult.getMsg());
                                if (httpResult.getStatus() == 200) {
                                    isSave = false;
                                    setResult(Config.REFRESH);
                                    finish();
                                }
                            }
                        });
            } else {
                ToastUtil.showShort(msg);
            }
        });
    }


    @Override
    protected RecyclerView initRecyclerView() {
        return dataBinding.recyclerView;
    }

    @Override
    public void itemClick(int p) {
        switch (slimAdapterEx.getDataItem(p).getPosition()) {
            case 0:
                bundle = new Bundle();
                bundle.putBoolean(Config.IS_SELECT, true);
                startActivityForResult(TrainLectureListActivity.class, bundle, Config.LECTURE_LIST);
                break;
            case 5:
                if (bottomSheet == null) {
                    bottomSheet = BottomSheetUtil.getBottomSheet(this, "", (recyclerView, position, v) -> {
                        guid ="";
                        bottomSheet.dismiss();
                        switch (position) {
                            case 0:
                                startActivityForResult(SelectTeacherActivity.class, null, Config.SELECT_TEACHER);
                                break;
                            case 1:
                                startActivityForResult(SelectSingleStaffActivity.class, null, Config.SELECT_SINGLE_STAFF);
                                break;
                            case 2:
                                SlimEditEnterBean slimEditEnterBean = (SlimEditEnterBean) slimAdapterEx.getDataItem(5);
                                bundle = new Bundle();
                                bundle.putString("content", slimEditEnterBean.getContent());
                                bundle.putString("tip", TextUtils.isEmpty(slimEditEnterBean.getTip()) ? slimEditEnterBean.getTitle() : slimEditEnterBean.getTip());
                                bundle.putString("title", slimEditEnterBean.getTitle());
                                bundle.putBoolean("canBlank", slimEditEnterBean.isCanBlank());
                                AppConstent.schemes = slimEditEnterBean.getSchemes();
                                startActivityForResult(EditTextActivity.class, bundle, p);
                                break;
                        }
                    }, "在线讲师", "企业内部", "其它");
                }
                bottomSheet.show();
                break;
            case 8:
                bundle = new Bundle();
                bundle.putParcelableArrayList(Config.LIST, timeBeans);
                startActivityForResult(AddTrainTimesActivity.class, bundle, Config.ADD_TRAIN_TIMES);
                break;
        }
    }

    @Override
    protected void setEditBeans() {
        isSave = false;
        isRead = false;
        datas.add(new SlimEditEnterBean("*培训主题", "", 0, true, "请选择").setNeed(true));
        datas.add(new SlimEditHintBean("*培训类别", "", 1).setNeed(true));
        datas.add(new SlimEditHintBean("*培训对象", "", 2).setNeed(true));
        datas.add(new SlimEditHintBean("*预算费用", "", 3));
        datas.add(new SlimEditEnterBean("*受训人数", "", 4, "").addSchemes(StaticScheme.Numeric()).setNeed(true));
        datas.add(new SlimEditHintBean("*人均费用", "", 5).setNeed(true));
        datas.add(new SlimEditEnterBean("*培训老师", "", 6, "请输入").setNeed(true));
        datas.add(new SlimEditChooseBean("学习形式", "", 7, "请选择", new String[]{"线下面授", "线下集体网络", "网络自学"}));
        datas.add(new SlimEditVEnterBean("*培训时间", "", 8, "添加").setDeal(true).setNeed(true));
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Config.LECTURE_LIST && resultCode == Config.SUCCESS) {
            trainListBean = (LectureListBean) data.getSerializableExtra(Config.BEAN);
            contracts = AppConstent.user.getGuid();
            slimAdapterEx.getDataItem(0).setContent(trainListBean.getCourseTheme());
            slimAdapterEx.notifyItemChanged(0);
            slimAdapterEx.getDataItem(1).setContent(trainListBean.getCourseType());
            slimAdapterEx.notifyItemChanged(1);
            slimAdapterEx.getDataItem(2).setContent(trainListBean.getPosts());
            slimAdapterEx.notifyItemChanged(2);
            slimAdapterEx.getDataItem(3).setContent(trainListBean.getCostbudget() + "");
            slimAdapterEx.notifyItemChanged(3);
            slimAdapterEx.getDataItem(6).setContent(trainListBean.getLectureIntroduce());
            slimAdapterEx.notifyItemChanged(6);

        } else if (resultCode == Config.SUCCESS && requestCode == Config.SELECT_POST_MULTI) {
            int num = data.getIntExtra(Config.NUM, 0);
            careerListBeans = data.getParcelableArrayListExtra(Config.SELECTED_BEANS);
            slimAdapterEx.getDataItem(3).setContent(num + "");
            StringBuilder stringBuilder = null;
            for (CareerListResultBean careerListBean : careerListBeans) {
                if (stringBuilder == null) {
                    stringBuilder = new StringBuilder(careerListBean.getName());
                } else {
                    stringBuilder.append(",").append(careerListBean.getName());
                }
            }
            stringBuilderDepId = null;
            stringBuilderDepName = null;
            Flowable.fromIterable(careerListBeans)
                    .distinct(CareerListResultBean::getDepartid)
                    .subscribe(integer -> {
                        if (stringBuilderDepName == null) {
                            stringBuilderDepName = new StringBuilder(integer.getDepartName());
                            stringBuilderDepId = new StringBuilder(integer.getDepartid() + "");
                        } else {
                            stringBuilderDepId.append(",").append(integer.getDepartid());
                            stringBuilderDepName.append(",").append(integer.getDepartName());
                        }
                    });
            slimAdapterEx.getDataItem(2).setContent(stringBuilder.toString());
            slimAdapterEx.notifyItemRangeChanged(2, 2);
            if (!TextUtils.isEmpty(slimAdapterEx.getDataItem(5).getContent())) {
                int totalMoney = Integer.parseInt(setParam(5));
                double avrMoney = totalMoney / num;
                slimAdapterEx.getDataItem(6).setContent(avrMoney + "");
                slimAdapterEx.notifyItemChanged(6);
            }
        } else if (requestCode == Config.SELECT_SINGLE_STAFF && resultCode == Config.INTENT_CONTENT) {
            EmploymentListResultBean staff = (EmploymentListResultBean) data.getSerializableExtra(Config.BEAN);
            guid = staff.getGuid();
            slimAdapterEx.getDataItem(6).setContent(staff.getStaffName());
            slimAdapterEx.notifyItemChanged(6);
        } else if (requestCode == Config.ADD_TRAIN_TIMES && resultCode == Config.SUCCESS) {
            timeBeans = data.getParcelableArrayListExtra(Config.LIST);
            StringBuilder timeStrs = null;
            StringBuilder stringBuilder = null;
            for (AddTrainTimesActivity.RangeTimeBean timeBean : timeBeans) {
                if (stringBuilder == null) {
                    stringBuilder = new StringBuilder(timeBean.getDate() + " " + timeBean.getFrom() + "~" + timeBean.getTo());
                    timeStrs = new StringBuilder(timeBean.getDate() + " " + timeBean.getFrom() + "~" + timeBean.getTo());
                } else {
                    stringBuilder.append(",").append(timeBean.getDate() + " " + timeBean.getFrom() + "~" + timeBean.getTo());
                    timeStrs.append("\r\n").append(timeBean.getDate() + " " + timeBean.getFrom() + "~" + timeBean.getTo());
                }
            }
            times = stringBuilder.toString();
            slimAdapterEx.getDataItem(8).setContent(timeStrs.toString());
            slimAdapterEx.notifyItemChanged(8);
        } else if (requestCode == Config.SELECT_TEACHER && resultCode == Config.SUCCESS) {
            TeacherListBean teacherListBean = (TeacherListBean) data.getSerializableExtra(Config.BEAN);
            guid = teacherListBean.getUserGuid();
            slimAdapterEx.getDataItem(6).setContent(teacherListBean.getRealname());
            slimAdapterEx.notifyItemChanged(6);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 4 && resultCode == Config.INTENT_CONTENT) {
                if (!TextUtils.isEmpty(setParam(3).trim())) {
                    int num = Integer.parseInt(data.getStringExtra(Config.CONTENT));
                    Double totalMoney = Double.parseDouble(setParam(3));
                    double avrMoney = totalMoney / num;
                    slimAdapterEx.getDataItem(5).setContent(new DecimalFormat("0.00").format(avrMoney));
                    slimAdapterEx.notifyItemChanged(5);
                }
            }
        }
    }
}
